/**
 * 
 */
package com.cnhaimei.vod.logic;

import java.io.File;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.cnhaimei.com.VODLog;
import com.cnhaimei.com.qrcode.CaptureActivity;
import com.cnhaimei.vod.LocalRoomsManager;
import com.cnhaimei.vod.MyActivityManager;
import com.cnhaimei.vod.R;
import com.cnhaimei.vod.bean.Room;
import com.cnhaimei.vod.net.DCHeart;
import com.cnhaimei.vod.net.DQHeart;
import com.cnhaimei.vod.net.NetManager;
import com.cnhaimei.vod.net.XVod;
import com.cnhaimei.vod.util.Const;
import com.cnhaimei.vod.util.Ftp;
import com.cnhaimei.vod.util.Http;
import com.cnhaimei.vod.util.ImageLoader;
import com.cnhaimei.vod.util.IniFile;
import com.cnhaimei.vod.util.Util;
import com.cnhaimei.vod.util.ZipToFile;

/**
 * home
 * 
 * @author jin001.wu@gmail.com <br>
 * @date 2011-7-8
 * 
 */
public class HomeActivity extends VODActivity {

	private boolean mTypeChooseDialogShowed;//版本选择窗口是否已经显示
	private EditText mIpInput = null;//ip输入框
	private int mImageViewHeight = 184;
	private int mImageViewWidth = 185;
	
	private AlertDialog mTypeChooseDialog;
	private AlertDialog mIpInputDialog;
	private String mCurrentIp;
	private int mCurType = 0;//0-单机输入ip方式，1-二维码网络连接方式，2-网络版， 3-单机注册版
	
	private static String TAG = "HomeActivity";
	
	private static boolean mIsReConnect = false;//是否重新绑定房台
	
	private boolean mShowRooms = false;
	
	private static boolean mIsCheckUpdated = false;
	
	public static void doReConnectServer() {
		if (Util.VLOG) {
			VODLog.e(TAG, "doReConnectServer");
		}
		MyActivityManager.G().goTop();
		mIsReConnect = true;
	}
	
	//是否重新绑定房台
	public static boolean getIsReconnect() {
		return mIsReConnect;
	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		if (mIsReConnect) {
			mIsReConnect = false;

			resetState();
			NetManager.G().closeAll();
    		showTypeChooseDialog();
		}
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.v8_standalone_home);

		DCHeart.setRegDstIp(Util.getBroadcastIp(this));
		
		setClickable( R.id.song, R.id.singer, R.id.barsong, R.id.film, R.id.favorites, R.id.hotrank);
		
		updatePosition();
		
		showTypeChooseDialog();

//		View home = findViewById(R.id.home);
//		home.setBackgroundResource(R.drawable.home_active);

//		DisplayMetrics dm = getResources().getDisplayMetrics();
//		int wPix = dm.widthPixels;
//		int hPix = dm.heightPixels;

//		float w = dm.widthPixels / dm.xdpi;
//		float h = dm.heightPixels / dm.ydpi;
//		double inch = Math.sqrt(h * h + w * w);
		
//		Log.e("size:", "w:" + dm.widthPixels + " h:" + dm.heightPixels + "density:" + dm.density);
//		
//		Log.e("size1:", "w:" + w + " h:" + h + "inch:" + inch);
	}
	
	//调整中间6个板块的位置
	private void updatePosition()
	{
		DisplayMetrics dMetrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dMetrics);
		float xdpi = dMetrics.widthPixels;//dMetrics.xdpi;
		float ydpi = dMetrics.heightPixels;//dMetrics.ydpi;
		float fScaleX = xdpi / 480;//xdpi / 240;
		float fScaleY = ydpi / 800;//ydpi / 240;
		
		float fTopBottomScale = xdpi / 540;
		int nHeadHeight = (int)(98 * fTopBottomScale);//(int) (98 * fScaleY);
		int nFootHeight = (int)(116 * fTopBottomScale);//(int) (116 * fScaleY);		
		int nPanelHeight = dMetrics.heightPixels - nHeadHeight - nFootHeight;
		int nPaddingTop = (int)((nPanelHeight - (mImageViewHeight*3 - 22) * fScaleY) / 2);
		View layout = findViewById(R.id.HomeTableLayout);
		layout.setPadding(0, nPaddingTop, 0, 0);
		
		int nPaddingX = (int)((dMetrics.widthPixels - (mImageViewWidth + 20)*fScaleX*2)/4);
		updateImageViewPos(fScaleX, fScaleY, nPaddingX, R.id.song, R.id.singer, R.id.barsong, R.id.film, R.id.favorites, R.id.hotrank);		
	}

	protected void updateImageViewPos(float fScaleX, float fScaleY, int paddingX, int... ids) {
		for (int i = 0; i < ids.length; i++) {
			View v = findViewById(ids[i]);
			if (v != null)
			{
				ViewGroup.LayoutParams lp = v.getLayoutParams();
				lp.height = (int)((int)mImageViewHeight * fScaleY);
				lp.width = (int) ((int)mImageViewWidth * fScaleX + paddingX*2);
				v.setLayoutParams(lp);
				((ImageView)v).setScaleType(ScaleType.FIT_XY);
				v.setPadding(paddingX, 0, paddingX, 0);
			}
		}
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode)
		{
		case Const.RequestCode.ROOMS:
			if (resultCode == RESULT_CANCELED)
			{
				resetState();
        		showTypeChooseDialog();
				return;
			}			
			if (mTypeChooseDialog != null) {
				mTypeChooseDialog.dismiss();
				mTypeChooseDialogShowed = false;
				mTypeChooseDialog = null;
			}
			break;
		case Const.RequestCode.MORE_SETTING:
			if (resultCode == Const.ResultCode.RECHOOSE_ROOM)
			{
				if (Util.VLOG) {
					VODLog.e(TAG, "doReConnectServer");
				}
				resetState();
				NetManager.G().closeAll();
        		showTypeChooseDialog();
			}
			break;
		case Const.RequestCode.QR_CODE:
			if (resultCode == RESULT_CANCELED)
			{
        		showTypeChooseDialog();
				return;
			}
        	mCurType = 1;
			String strIp = data.getStringExtra("qrcode");
			Log.e(TAG, "qrcode:" + strIp);
			int index = strIp.indexOf(',');
			if (index == 1) {
				String typeString = strIp.substring(0, 1);
				if (typeString.equalsIgnoreCase("s")) {
		        	mCurType = 0;
				}
				
				strIp = strIp.substring(index + 1);
				index = strIp.indexOf(':');
			}
			if (index > 0) {
				pas = strIp.substring(index + 1, index + 5);
				strIp = strIp.substring(0, index);
			}				
        	checkAndEnter(strIp);
			break;
		case Const.RequestCode.LOCAL_ROOMS:
			if (resultCode == RESULT_CANCELED)
			{
        		showTypeChooseDialog();
				return;
			}
			if (resultCode == RESULT_OK) {
				mCurType = 0;
				mCurrentIp = LocalRoomsManager.G().getSelectedIp();
				if (mCurrentIp != null && mCurrentIp.length() > 0) {
					checkAndEnter(mCurrentIp);
				}
			}
			break;
		}
	}
	
	//执行网络版
	private void processNetType()
	{
		mCurType = 2;
		checkAndEnter("");
	}

	//执行二维码版
	private void processQRCodeType()
	{
		Intent bintent = new Intent(this, CaptureActivity.class);
		startActivityForResult(bintent, Const.RequestCode.QR_CODE); 
	}
	
	//执行本地注册版
	private void processLocalRegisterType()
	{
		mCurType = 3;
		checkAndEnter("");
	}

	//“单机版”和“网络版”选择框
	public void showTypeChooseDialog()
	{
		if (mTypeChooseDialogShowed) {
			return;
		}
		mTypeChooseDialogShowed = true;
		mTypeChooseDialog = new AlertDialog.Builder(this)
        /* 弹出窗口的最上头文字 */
        .setTitle(R.string.tip_title)
        /* 设置弹出窗口的信息 */
        .setMessage(R.string.type_choose_msg)
        .setPositiveButton(R.string.type_qrcode,
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialoginterface, int i) {
                        //TODO：执行网络版操作
                    	mTypeChooseDialogShowed = false;
                    	mTypeChooseDialog.dismiss();
                    	//TODO:临时用
                    	//mCurType = 1;
                    	processQRCodeType();
                    	//processNetType();
                    }
                })
        .setNegativeButton(R.string.type_local_ver,
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialoginterface, int i) {
                    	//TODO：执行单机版操作
                    	
                    	mTypeChooseDialogShowed = false;
                    	mTypeChooseDialog.dismiss();
//                    	mCurType = 0;
                		showIpInputDialog();

                    	
                    }
                })
        .setNeutralButton(R.string.type_net_ver, 
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialoginterface, int i) {
                    	//TODO：执行网络版操作
                    	mTypeChooseDialogShowed = false;
                    	mTypeChooseDialog.dismiss();
                    	processNetType();
                    }
                })
        .setOnKeyListener(new DialogInterface.OnKeyListener() {			
			public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
				// TODO Auto-generated method stub
				
                if (keyCode == KeyEvent.KEYCODE_BACK  
                        && event.getAction() == KeyEvent.ACTION_UP) { 

        			confirmFinish();
                    return true;
                } 
                
				return false;
			}
		})
        .show();
        mTypeChooseDialog.setCanceledOnTouchOutside(false);

	}
	
	private ProgressDialog mProgressDialog;
	//定义Handler对象
	private Handler mWaitIpHandler =new Handler(){
	   @Override
	   //当有消息发送出来的时候就执行Handler的这个方法
	   public void handleMessage(Message msg){
	      super.handleMessage(msg);
	      try {
		      //只要执行到这里就关闭对话框
		      mProgressDialog.dismiss();
	      }
	      catch(Exception e)
	      {
	    	  
	      }
	   }
	};
	
	private void checkAndEnter(String strIp)
	{
	    //构建一个等待进度条
		mProgressDialog = ProgressDialog.show(this, null, getResources().getString(R.string.waiting_for_connect));
		mProgressDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {			
			public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
				// TODO Auto-generated method stub
                if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK) { 
                	//TODO：返回类型选择对话框
//                	if (3 == mCurType) {//单机注册版
//        				EventsManager.G().unRegisterListener(EventsManager.Event.REGISTER_ROOMS, HomeActivity.this);
//        				myHandler.removeMessages(MSG_TIME_OUT);
//        				mWaitIpHandler.sendEmptyMessage(0);
//        				showTypeChooseDialog();
//					}
//                	else {
//                    	confirmFinish();
//					}

        			NetManager.G().closeAll();
        			resetState();
        			
    				EventsManager.G().unRegisterListener(EventsManager.Event.REGISTER_ROOMS, HomeActivity.this);
    				myHandler.removeMessages(MSG_TIME_OUT);
    				mWaitIpHandler.sendEmptyMessage(0);
    				showTypeChooseDialog();
                }  
				return false;
			}
		});
		mCurrentIp = strIp;

		switch(mCurType){
		case 0://单机版
			processConnect(strIp);
			break;
		case 1://二维码版
			processQRCodeConnect(strIp);
			break;
		case 2://网络版
			processNetTypeConnect();			
			break;
		case 3://单机注册版
			processRegisterConnect();
			break;
		default:
			break;
		}
	}

	private Handler myHandler = new  Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case MSG_TIME_OUT:
				myHandler.removeMessages(MSG_TIME_OUT);
				isOutTime = true;
				mWaitIpHandler.sendEmptyMessage(0);
				showTypeChooseDialog();
				Toast.makeText(HomeActivity.this, R.string.read_room_error, Toast.LENGTH_SHORT).show();
				break;

			default:
				break;
			}
		}
		
	};

	private final static long TIME_OUT = 60 * 1000;
	private final static int MSG_TIME_OUT = 1;
	Room room;
	int dcManagerId;
	int dqManagerId;
	String pas;
	boolean isOutTime;
	boolean isSilent;
	private int dcHeartId;
	private int dqHeartId;
	private boolean dqHearConnected = false;
	private boolean dqConnected = false;
	private String[] rooms;
	private boolean roomsGetted = false;
	private boolean bQRPasswordSended = false;
	private void resetState() {
		dqHearConnected = false;
		dqConnected = false;
		roomsGetted = false;
		mShowRooms = false;
		rooms = null;
		bQRPasswordSended = false;
		mCurType = -1;
		pas = "";
	}
	
	//执行连接操作
	private void processConnect(String strIp)
	{
		if (Util.VLOG) {
			VODLog.e(TAG, "processConnect()");
		}
		myHandler.sendEmptyMessageDelayed(MSG_TIME_OUT, TIME_OUT);
		room = new Room();
		
		XVod.G().unRegisterListener(EventsManager.Event.ROOM_INFO, this);
		XVod.G().unRegisterListener(EventsManager.Event.DISCONNECT,this);		
		
		Log.e(getClass().getName(), "ip = " + strIp);
		XVod.G().registerListener(EventsManager.Event.CONNECTING,this);
		XVod.G().registerListener(EventsManager.Event.DISCONNECT,this);
		XVod.G().registerListener(EventsManager.Event.CHCKD_PAS, this);
		room.setIp(strIp);
		
		isSilent = true;
		//NetManager.G().close(NetManager.G().getDCManangerId()); // 事先关闭
		dcManagerId = NetManager.G().startDCManager(strIp);
		dqManagerId = NetManager.G().startDQManager(strIp);
	}

	//执行二维码版连接操作
	private void processQRCodeConnect(String strIp)
	{
		if (Util.VLOG) {
			VODLog.e(TAG, "processQRCodeConnect()");
		}
		myHandler.sendEmptyMessageDelayed(MSG_TIME_OUT, TIME_OUT);
		room = new Room();
		
		//dcHeartId = NetManager.G().startDCHeart(); // 启动网络
		dqHeartId = NetManager.G().startDQHeart(); // need
		
		XVod.G().unRegisterListener(EventsManager.Event.ROOM_INFO, this);
		Log.e(getClass().getName(), "ip = " + strIp);
		XVod.G().registerListener(EventsManager.Event.CONNECTING,this);
		XVod.G().registerListener(EventsManager.Event.DISCONNECT,this);
		XVod.G().registerListener(EventsManager.Event.CHCKD_PAS, this);
		room.setIp(strIp);
		
		isSilent = true;
		dcManagerId = NetManager.G().startDCManager(strIp);
	}

	//执行网络版连接操作
	private void processNetTypeConnect()
	{		
		if (Util.VLOG) {
			VODLog.e(TAG, "processNetTypeConnect()");
		}
		
		resetState();
		NetManager.G().closeAll();
		
		myHandler.sendEmptyMessageDelayed(MSG_TIME_OUT, TIME_OUT);
		room = new Room();
		
		dcHeartId = NetManager.G().startDCHeart(); // 启动网络
		dqHeartId = NetManager.G().startDQHeart(); // need

		XVod.G().registerListener(EventsManager.Event.ROOMS, this);
		XVod.G().unRegisterListener(EventsManager.Event.ROOM_INFO, this);
		XVod.G().registerListener(EventsManager.Event.CONNECTING,this);
		XVod.G().registerListener(EventsManager.Event.DISCONNECT,this);
		XVod.G().registerListener(EventsManager.Event.CHCKD_PAS, this);
		
		isSilent = true;
		//NetManager.G().close(NetManager.G().getDCManangerId()); // 事先关闭
		//dcManagerId = NetManager.G().startDCManager(strIp);
		//dqManagerId = NetManager.G().startDQManager(strIp);
	}
	
	private void processRegisterConnect()
	{
		if (Util.VLOG) {
			VODLog.e(TAG, "processRegisterConnect()");
		}
		myHandler.sendEmptyMessageDelayed(MSG_TIME_OUT, TIME_OUT);
		LocalRoomsManager.G().clearRooms(); 
		
		XVod.G().unRegisterListener(EventsManager.Event.ROOM_INFO, this);
		XVod.G().unRegisterListener(EventsManager.Event.REGISTER_ROOMS, this);
		
		dcHeartId = NetManager.G().startDCHeart(DCHeart.REG_PORT); // 启动网络
		dqHeartId = NetManager.G().startDQHeart(); // need

		XVod.G().registerListener(EventsManager.Event.CONNECTING,this);
		XVod.G().registerListener(EventsManager.Event.DISCONNECT,this);
		XVod.G().registerListener(EventsManager.Event.REGISTER_ROOMS,this);
		
		requestRegRooms();
	}

	private void requestGetRooms() {
		XVod.G().downloadRooms();
	}
	
	//单机版请求注册
	private void requestRegRooms() {
		DCHeart.setRegDstIp(Util.getBroadcastIp(this));
		XVod.G().requestRegRooms();
	}
	
	public void onEvent(int event, Object obj, boolean isSuc) {
		switch (event) {
			case EventsManager.Event.PLYER_STATE:
				super.onEvent(event, obj, isSuc);
				break;
			case EventsManager.Event.CHCKD_PAS: {
				if (Util.VLOG) {
					VODLog.e(TAG, "onEvent(). EventsManager.Event.CHCKD_PAS: isSuc=" + (isSuc ? "true" : "false"));
				}
//				isSuc = true;
//				if (mIsReconnected) {
//					isSuc = true;
//				}
				if (isSuc) {
					setResult(RESULT_OK);
					XVod.G().startKeepPlayerHeart();

					Toast.makeText(this, getString(R.string.connect_success), Toast.LENGTH_SHORT).show();
					
					myHandler.removeMessages(MSG_TIME_OUT);
					mWaitIpHandler.sendEmptyMessage(0);
					if (mIpInputDialog != null){
						mIpInputDialog.dismiss();
					}
					
					//检查是否需要更新明星图片资源
					if (!mIsCheckUpdated) {
						if (Util.VLOG) {
							VODLog.e(TAG, "start check package update. runDownload().");
						}
						mIsCheckUpdated = true;
						runDownload();
					}
				} 
				else {
					/*
					mWaitIpHandler.sendEmptyMessage(0);
					
					myHandler.removeMessages(MSG_TIME_OUT);
					String s = getString(R.string.password_wrong);
					if (obj instanceof String) {
						s = (String)obj;
						if (s.equals("server not open")) {
							s = getString(R.string.server_not_open);
						} else if (s.startsWith("password error")) {
							s = getString(R.string.password_error);
						}
					}
				
					Toast.makeText(this, s, Toast.LENGTH_SHORT).show();
					*/
				}
			}
				break;
			case EventsManager.Event.CONNECTING: {//连接上
				if (obj != null && obj instanceof Integer) {
					int id = (Integer) obj;
					if (Util.VLOG) {
						VODLog.e(TAG, "onEvent(). EventsManager.Event.CONNECTING., i = " + String.valueOf(id));
					}
					Log.e(TAG, "EventsManager.Event.CONNECTING, i = " + String.valueOf(id));
					if (id == dcManagerId) {
						if (mCurType != 2 && mCurType != 1) 
						{
							XVod.G().unRegisterListener(EventsManager.Event.CONNECTING, this);
						}

						if (dqConnected && mCurType == 1 && pas != null && pas.length() > 0) {
							if (!bQRPasswordSended) {
								if (Util.VLOG) {
									VODLog.e(TAG, "onEvent(). mCurType == 1 && pas != null && pas.length() > 0 && !bQRPasswordSended");
									VODLog.e(TAG, "onEvent(). pas=" + pas);
								}
								bQRPasswordSended = true;
								XVod.G().passwordCheck(pas);
							}
						}	
					}
					if (id == dcHeartId) {
						Log.e(TAG, "dcHeartId");
						if (Util.VLOG) {
							VODLog.e(TAG, "onEvent(). EventsManager.Event.CONNECTING., id = dcHeartId");
						}
						if (mCurType == 2) {
							requestGetRooms(); // 请求房间数据							
						}
					} 
					else if (id == dqHeartId && !dqHearConnected) {
						if (Util.VLOG) {
							VODLog.e(TAG, "onEvent(). EventsManager.Event.CONNECTING:id == dqHeartId && !dqHearConnected");
						}
						Log.e(TAG, "dqHeartId");
						String strIp = DQHeart.getVODServerIP();
						if (strIp != null) {
							if (Util.VLOG) {
								VODLog.e(TAG, "onEvent(). DQHeart.getVODServerIP() != null");
							}
							dqHearConnected = true;
							dqManagerId = NetManager.G().startDQManager(strIp);
						}
					} 
					else if (id == dqManagerId) {
						Log.e(TAG, "dqmanagerid");
						if (Util.VLOG) {
							VODLog.e(TAG, "onEvent(). EventsManager.Event.CONNECTING., id = dqManagerId");
						}
						dqConnected = true;
						// loaddingFinished();
						// Intent i = new Intent(Const.Action.LoadingFinsihed);
						// i.putExtra(Const.Key.ROOM_LIST, rooms);
						// startActivity(i);
						//checkAndEnter(false);

						if (mCurType == 1 && pas != null && pas.length() > 0) {
							if (!bQRPasswordSended) {
								if (Util.VLOG) {
									VODLog.e(TAG, "onEvent(). mCurType == 1 && pas != null && pas.length() > 0 && !bQRPasswordSended");
									VODLog.e(TAG, "onEvent(). pas=" + pas);
								}
								bQRPasswordSended = true;
								XVod.G().passwordCheck(pas);
							}
						}						
						
						if (dqConnected && roomsGetted && !mShowRooms) {
							mShowRooms = true;
							Log.e(TAG, "EventsManager.Event.CONNECTING, dqConnected && roomsGetted");
							if (Util.VLOG) {
								VODLog.e(TAG, "onEvent(). EventsManager.Event.CONNECTING, dqConnected && roomsGetted");
							}
							Intent i = new Intent(Const.Action.LoadingFinsihed);
							i.putExtra(Const.Key.ROOM_LIST, rooms);
							startActivityForResult(i, Const.RequestCode.ROOMS);
							myHandler.removeMessages(MSG_TIME_OUT);
							mWaitIpHandler.sendEmptyMessage(0);
							if (mIpInputDialog != null){
								mIpInputDialog.dismiss();
							}
							if (mTypeChooseDialog != null) {
								mTypeChooseDialog.dismiss();
								mTypeChooseDialogShowed = false;
								mTypeChooseDialog = null;
							}
						}
					}
					else {
						Log.e(TAG, "EventsManager.Event.CONNECTING");
						if (Util.VLOG) {
							VODLog.e(TAG, "onEvent(). EventsManager.Event.CONNECTING.");
						}

//						if (mCurType == 1 && pas != null && pas.length() > 0) {
//							XVod.G().passwordCheck(pas);
//						}
					}
				} 
				else {
					myHandler.removeMessages(MSG_TIME_OUT);
					mWaitIpHandler.sendEmptyMessage(0);
					showIpInputDialog();
				}
			}
			break;
			case EventsManager.Event.DISCONNECT: {//连接失败
				if (obj != null && obj instanceof Integer) {
					int id = (Integer) obj;
					if (Util.VLOG) {
						VODLog.e(TAG, "onEvent(). EventsManager.Event.DISCONNECT. id = " + id);
					}
					if (id == dcManagerId) {
						XVod.G().unRegisterListener(EventsManager.Event.DISCONNECT, this);
						myHandler.removeMessages(MSG_TIME_OUT);
						mWaitIpHandler.sendEmptyMessage(0);
						if (!isSilent) {
							Toast.makeText(HomeActivity.this,
									R.string.connecting_dc_error,
									Toast.LENGTH_SHORT).show();
							isSilent = false;
						}
						Util.showMyToast(HomeActivity.this, getString(R.string.connecting_dc_error), 3);
						//showIpInputDialog();
						showTypeChooseDialog();
					}
				}
			}
			break;
			case EventsManager.Event.ROOMS:
				Log.e(TAG, "EventsManager.Event.ROOMS");
				if (isSuc && obj != null && rooms == null) {
					Log.e(TAG, "EventsManager.Event.ROOMS, isSuc && obj != null && rooms == null");
					if (Util.VLOG) {
						VODLog.e(TAG, "onEvent(). EventsManager.Event.ROOMS, isSuc && obj != null && rooms == null");
					}
					EventsManager.G().unRegisterListener(event, this);
					rooms = (String[]) obj;
					roomsGetted = true;
					if (dqConnected && roomsGetted && !mShowRooms) {
						mShowRooms = true;
						Log.e(TAG, "EventsManager.Event.ROOMS, dqConnected && roomsGetted");
						Intent i = new Intent(Const.Action.LoadingFinsihed);
						i.putExtra(Const.Key.ROOM_LIST, rooms);
						startActivityForResult(i, Const.RequestCode.ROOMS);
						myHandler.removeMessages(MSG_TIME_OUT);
						mWaitIpHandler.sendEmptyMessage(0);
						if (mIpInputDialog != null){
							mIpInputDialog.dismiss();
						}
						if (mTypeChooseDialog != null) {
							mTypeChooseDialog.dismiss();
							mTypeChooseDialogShowed = false;
							mTypeChooseDialog = null;
						}
					}
				}
				break;
			case EventsManager.Event.REGISTER_ROOMS:
				EventsManager.G().unRegisterListener(event, this);
				/*
				String strData = (String)obj;
				if (strData != null && strData.length() > 0) {
					int index = strData.indexOf(',');
					if (index > 0) {
						String strIp = strData.substring(0, index);
						String strRoomName = strData.substring(index + 1).replace(';', ' ').trim();

						mCurType = 1;
						mCurrentIp = strIp;
						checkAndEnter(strIp);
					}
				}
				*/
				myHandler.removeMessages(MSG_TIME_OUT);
				mWaitIpHandler.sendEmptyMessage(0);
				startActivity(Const.Action.ShowLocalRooms, Const.RequestCode.LOCAL_ROOMS);
				
				break;
			default:
				break;
		}

	}
	

	//“单机版”ip择框
	private void showIpInputDialog()
	{
		if (mIpInputDialog != null)
		{
			mIpInputDialog.dismiss();
		}
		
		Builder dialog = new AlertDialog.Builder(this);
		LayoutInflater inflater = (LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		LinearLayout layout = (LinearLayout)inflater.inflate(R.layout.v8_edit_view, null);
		dialog.setView(layout);
		mIpInput = (EditText)layout.findViewById(R.id.ip_input);
		final View ipLayout = layout.findViewById(R.id.ip_layout);
		View bt = layout.findViewById(R.id.auto_search_rooms);
		bt.setOnClickListener(new OnClickListener() {			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				//自动搜索包厢
            	mIpInputDialog.dismiss();				

            	/*
				rooms = new String[30]; // TODO test
				Room room = null;
				for (int i1 = 0; i1 < rooms.length; i1++) {
					rooms[i1] = "测试" + String.valueOf(i1);
					room = LocalRoomsManager.parse("192.168.1.100," + rooms[i1]);
					LocalRoomsManager.G().addRoom(room);
				}
				startActivity(Const.Action.ShowLocalRooms, Const.RequestCode.LOCAL_ROOMS);
				*/
            	processLocalRegisterType();//processRegisterConnect();
			}
		});
		CheckBox chkBox = (CheckBox)layout.findViewById(R.id.checkbox_ipinput);
		if (chkBox != null) {
			chkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
				
				@Override
				public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
					// TODO Auto-generated method stub
					if (isChecked) {
						ipLayout.setVisibility(View.VISIBLE);						
					}
					else {
						ipLayout.setVisibility(View.GONE);
					}
				}
			});
		}
		View okBtn = layout.findViewById(R.id.ok);
		okBtn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
            	if (mIpInput != null)
            	{
            		String strIp = mIpInput.getText().toString();
            		if (strIp.length() == 0)
            		{
            			strIp = mIpInput.getHint().toString();            			
            		}
            		pas = "";
            		mCurType = 0;
            		checkAndEnter(strIp);
            	}
			}
		});
		View cancelBtn = layout.findViewById(R.id.cancel);
		cancelBtn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
            	mIpInputDialog.dismiss();
            	showTypeChooseDialog();
			}
		});
		//dialog.setTitle(R.string.ip_input_tip);
		/*
		dialog.setPositiveButton(R.string.ok,
                new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialoginterface, int i) {
                
            	if (mIpInput != null)
            	{
            		String strIp = mIpInput.getText().toString();
            		if (strIp.length() == 0)
            		{
            			strIp = mIpInput.getHint().toString();            			
            		}
            		pas = "";
            		mCurType = 0;
            		checkAndEnter(strIp);
            	}
            }
        });
		dialog.setNegativeButton(R.string.cancel,
                new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialoginterface, int i) {
            	//TODO：返回类型选择对话框
            	mIpInputDialog.dismiss();
            	showTypeChooseDialog();
            }
        });
        */
		dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {			
			public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
				// TODO Auto-generated method stub
                if (keyCode == KeyEvent.KEYCODE_BACK  
                        && event.getAction() == KeyEvent.ACTION_UP) { 
                	//TODO：返回类型选择对话框
                	showTypeChooseDialog();
                }  
				return false;
			}
		});
		mIpInputDialog = dialog.show();
		mIpInputDialog.setCanceledOnTouchOutside(false);
	}
	
	
	@Override
	public void onClick(View v) {
		int id = v.getId();
		switch (id) {
		case R.id.song://歌曲点歌
			startActivity(Const.Action.ShowAllSongs);
			break;
		case R.id.singer://歌星点歌
			startActivity(Const.Action.ShowStars);//(Const.Action.showAllSingers);
			break;
		case R.id.barsong://酒吧音乐
			startActivity(Const.Action.showBarSongs);
			break;
		case R.id.film://电影欣赏
			startActivity(Const.Action.showFilms);
			break;
		case R.id.favorites://私人收藏
			startActivity(Const.Action.showFavorites);
			break;
		case R.id.hotrank://热门排行
			startActivity(Const.Action.showHotrank);
			break;
		default:
			super.onClick(v); // need parent
			break;
		}
	}
	
	protected void onClickHome() {
//		finish();
		//empty 
	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		switch (keyCode) {
		case KeyEvent.KEYCODE_BACK:
//			if (Util.TEST || Util.DEMO) {
//				setResult(RESULT_OK);
//			}
//				finish();
			confirmFinish();
			break;
		default:
			return super.onKeyDown(keyCode, event);
		}
		return true;
	}
	
	private void confirmFinish() {
		AlertDialog mAlertDialog = new AlertDialog.Builder(this).create();
		mAlertDialog.setIcon(android.R.drawable.ic_dialog_alert);
		mAlertDialog.setTitle(R.string.confirm_exit_title);
		mAlertDialog.setMessage(getString(R.string.confirm_exit));
		mAlertDialog.setButton(getString(R.string.yes),
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
//						mSelfActivity.finish();
						Util.exit();
					}
				});
		mAlertDialog.setButton2(getString(R.string.no),
				(DialogInterface.OnClickListener) null);
		mAlertDialog.show();
	}

	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}
	

	private ProgressDialog mDownloadProgressDialog;
	//定义Handler对象
	private Handler mWaitDownloadHandler =new Handler(){
	   @Override
	   //当有消息发送出来的时候就执行Handler的这个方法
	   public void handleMessage(Message msg){
	      super.handleMessage(msg);
	      try {
	    	  if (msg.what == 0) {
			      //只要执行到这里就关闭对话框
		    	  mDownloadProgressDialog.dismiss();
		    	  if (msg.obj != null && msg.obj instanceof String) {
			    	  showMyToast((String)msg.obj);
		    	  }
	    	  }
	    	  else {
	    		  if (msg.what == 1) {
	    			  mDownloadProgressDialog.show();	    			  
	    		  }
	    		  else {
	    			  mDownloadProgressDialog.hide();
	    		  }
		    	  if (msg.obj != null && msg.obj instanceof String) {
		    		  mDownloadProgressDialog.setMessage((String)msg.obj);
	    			  Toast.makeText(HomeActivity.this, (String)msg.obj, Toast.LENGTH_LONG).show();
		    	  }
	    	  }
	      }
	      catch(Exception e)
	      {
	    	  
	      }
	   }
	};
	
	private void runDownload()
	{
//		if (Util.getDownloadedPackageCount() > 0) {
//			return;
//		}
		
	    //构建一个等待进度条
		mDownloadProgressDialog = ProgressDialog.show(this, null, getResources().getString(R.string.wait_for_check_update));
		mDownloadProgressDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {			
			public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
				// TODO Auto-generated method stub
                if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK) { 
                	//TODO：返回类型选择对话框
                	confirmFinish();
                }  
				return false;
			}
		});
		
		doCheckDownload();
	}
	
	private int mCurSize;
	private int mTotalSize;
	private IniFile mIniFile;
	private boolean mUseFtp = true;
	private void doCheckDownload() {

		new Thread(){
			 @Override
			 public void run(){
				 //你要执行的方法

				 boolean bNeedUpdate = false;
				 
					File dic = Environment.getExternalStorageDirectory();
					String sdcardPath = dic.getAbsolutePath();
					String rootPath = sdcardPath + "/v8/";
					File rootFile = new File(rootPath);
					rootFile.mkdir();
					int nSize = Util.getDownloadedPackageCount();
					String ftpIp = NetManager.G().getDQManagerIp();//"192.168.1.15";////ftp ip
					String httpUrl = Const.PICS_PACKAGE_URL;//http网址
				 
					Ftp ftp = new Ftp();
					String fileNamePath = sdcardPath;
					String iniFileName = "config.txt";
					String ftpUserName = "userdownload";
					String ftpPwd = "123456";
					boolean bFtpRet = ftp.ftpDownload(ftpIp, "21", ftpUserName, ftpPwd, "", rootPath, iniFileName);
					int nTotalZipFile = 0;
					
                    if (bFtpRet) {
                    	try {
    						IniFile iniFile = new IniFile(rootPath + iniFileName);
    						String strValue = iniFile.getValue("Package", "total");
    						nTotalZipFile = Integer.parseInt(strValue);
    						mIniFile = iniFile;
    						mCurSize = nSize;
    						mTotalSize = nTotalZipFile;
    						if (nTotalZipFile > nSize) {    							    							
    							bNeedUpdate = true;
    							mUseFtp = true;
    							mDownloadPicsHandler.sendEmptyMessage(0);
							}
						} catch (Exception e) {
							// TODO: handle exception
						}
					}
                    else {
						//Http下载
                    	Http.downFileToLocal(httpUrl + iniFileName, rootPath + iniFileName);
                    	File file = new File(rootPath + iniFileName);
                    	if (file.exists()) {
                    		try {
        						IniFile iniFile = new IniFile(rootPath + iniFileName);
        						String strValue = iniFile.getValue("Package", "total");
        						nTotalZipFile = Integer.parseInt(strValue);
        						mIniFile = iniFile;
        						mCurSize = nSize;
        						mTotalSize = nTotalZipFile;
        						if (nTotalZipFile > nSize) {    							    							
        							bNeedUpdate = true;
        							mUseFtp = false;
        							mDownloadPicsHandler.sendEmptyMessage(0);
    							}					
							} catch (Exception e) {
								// TODO: handle exception
							}
						}
					}

                    if (!bNeedUpdate) {
                        mWaitDownloadHandler.sendEmptyMessage(0);
					}
			 }
		}.start();
	}
	
	private Handler mDownloadPicsHandler = new Handler(){
		   @Override
		   //当有消息发送出来的时候就执行Handler的这个方法
		   public void handleMessage(Message msg){
		      super.handleMessage(msg);
		      try {
		    	  if (msg.what == 0) {
			    	  confirmDownloadPics();
		    	  }
		    	  else if (msg.what == 1) {
                  	if (mUseFtp) {
                    	ftpDownloadPics();
					}
                  	else {
						httpDownloadPics();
					}
		    	  }
		      }
		      catch(Exception e)
		      {
		    	  
		      }
		   }
		};
	
	private AlertDialog mConfirmDownloadDialog;
	private void confirmDownloadPics() {

		mConfirmDownloadDialog = new AlertDialog.Builder(this)
        /* 弹出窗口的最上头文字 */
        .setTitle(R.string.tip_title)
        /* 设置弹出窗口的信息 */
        .setMessage(R.string.download_package_confirm)
        .setPositiveButton(R.string.ok,
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialoginterface, int i) {
                        //TODO：执行下载操作
                        mConfirmDownloadDialog.dismiss();
                        mDownloadPicsHandler.sendEmptyMessage(1);
                    }
                })
        .setNegativeButton(R.string.cancel,
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialoginterface, int i) {
                    	//TODO：执行取消操作

                        mWaitDownloadHandler.sendEmptyMessage(0);
                        mConfirmDownloadDialog.dismiss();
                    }
                })
        .setOnKeyListener(new DialogInterface.OnKeyListener() {			
			public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
				// TODO Auto-generated method stub
				
                if (keyCode == KeyEvent.KEYCODE_BACK  
                        && event.getAction() == KeyEvent.ACTION_UP) { 


                    mWaitDownloadHandler.sendEmptyMessage(0);
                } 
                
				return false;
			}
		})
        .show();
		mConfirmDownloadDialog.setCanceledOnTouchOutside(false);
	}
	
	private void ftpDownloadPics() {

		new Thread(){
			 @Override
			 public void run(){

					boolean bFtpRet = false;
					String strValue;
			    	Message msg = null;
			    	boolean bNeedUpdate = false;

					File dic = Environment.getExternalStorageDirectory();
					String sdcardPath = dic.getAbsolutePath();
					String rootPath = sdcardPath + "/v8/";
					Ftp ftp = new Ftp();
					String ftpIp = NetManager.G().getDQManagerIp();//"192.168.1.15";////ftp ip
					String httpUrl = Const.PICS_PACKAGE_URL;//http网址
				 
					String fileNamePath = sdcardPath;
					String iniFileName = "config.ini";
					String ftpUserName = "userdownload";
					String ftpPwd = "123456";
					try {
				        for (int i = mCurSize; i < mTotalSize; i++) {
				        	bNeedUpdate = true;
				        	msg = new Message();
				        	msg.what = 2;
				        	msg.obj = String.format(getString(R.string.wait_for_download_pics), mCurSize + 1, mTotalSize);
				            mWaitDownloadHandler.sendMessageDelayed(msg, 1);
				        	
				        	strValue = mIniFile.getValue("Package", String.valueOf(i));
				        	bFtpRet = ftp.ftpDownload(ftpIp,  "21", ftpUserName, ftpPwd, "", rootPath, strValue);

							if (bFtpRet) {
					        	msg = new Message();
				            	msg.what = 2;
				            	msg.obj = String.format(getString(R.string.wait_for_unzip_file), mCurSize + 1, mTotalSize);
				                mWaitDownloadHandler.sendMessage(msg);
				                
								//解压zip包
								ZipToFile.upZipFile(rootPath + strValue, rootPath);
	    						//删除zip包
	    						Util.deleteFile(rootPath + strValue);
	    						ImageLoader.G.clearBuffer();

								//记录已下载数目
								Util.setDownloadedPackageCount(++mCurSize);
							}
							else {
								break;
							}
						}
					} catch (Exception e) {
						// TODO: handle exception
						bFtpRet = false;
					}

					msg = new Message();
			    	msg.what = 0;
					if (!bFtpRet) {
			        	msg.obj = getString(R.string.update_pics_failed);
					}
					else {
			        	msg.obj = getString(R.string.update_pics_success);
					}
					ImageLoader.G.clearBuffer();
			        mWaitDownloadHandler.sendMessage(msg);
			 }
		}.start();
	}
	
	private void httpDownloadPics() {

		new Thread(){
			 @Override
			 public void run(){
				 //你要执行的方法

					boolean bHttpRet = true;
					String strValue;
			    	Message msg = null;
				 
					File dic = Environment.getExternalStorageDirectory();
					String sdcardPath = dic.getAbsolutePath();
					String rootPath = sdcardPath + "/v8/";
					File rootFile = new File(rootPath);
					rootFile.mkdir();
					String httpUrl = Const.PICS_PACKAGE_URL;//http网址
			
					//Http下载
            		try {
	                    for (int i = mCurSize; i < mTotalSize; i++) {
	    					msg = new Message();
	                    	msg.what = 2;
	                    	msg.obj = String.format(getString(R.string.wait_for_download_pics), mCurSize + 1, mTotalSize);
	                        mWaitDownloadHandler.sendMessage(msg);
	                    	
	                    	strValue = mIniFile.getValue("Package", String.valueOf(i));
	                    	bHttpRet = Http.downFileToLocal(httpUrl + strValue, rootPath + strValue);

	                    	if (bHttpRet) {
		    					msg = new Message();
		                    	msg.what = 2;
		                    	msg.obj = String.format(getString(R.string.wait_for_unzip_file), mCurSize + 1, mTotalSize);
		                        mWaitDownloadHandler.sendMessage(msg);
								//解压zip包
	    						ZipToFile.upZipFile(rootPath + strValue, rootPath);
	    						//删除zip包
	    						Util.deleteFile(rootPath + strValue);
	    						ImageLoader.G.clearBuffer();

		    					//记录已下载数目
		    					Util.setDownloadedPackageCount(++mCurSize);								
							}
	                    	else {
								break;
							}
	                    }								
					} catch (Exception e) {
						// TODO: handle exception
						bHttpRet = false;
					}

					msg = new Message();
			    	msg.what = 0;
					if (!bHttpRet) {
			        	msg.obj = getString(R.string.update_pics_failed);
					}
					else {
			        	msg.obj = getString(R.string.update_pics_success);
					}
					ImageLoader.G.clearBuffer();
			        mWaitDownloadHandler.sendMessage(msg);
			 }
		}.start();
	}
	
}
